import { defineStore } from 'pinia'
import { ref } from 'vue'
import MenuApi from '@/api/menu.js'

const modules = import.meta.glob('@/views/**/*.vue')

const routeMap = new Map()
const root = {
  id: 0,
  parentId: null,
  path: '',
  children: [],
  fullPath: ''
}
routeMap.set(0, root)

const leafRoutes = ref([])

//todo: 用户拥有的权限，应该从后端获取，这里只是测试
const perms = new Set()
perms.add('sys:menu:list')
perms.add('sys:role:list')
perms.add('test:list')

export const usePermissionStore = defineStore('menu', () => {
  //仅供侧边栏使用
  const menus = ref([])
  const needLoadRoutes = ref(true)

  const getRoutes = async () => {
    let { data } = await MenuApi.routes()
    root.children = data
    filterRoutes(root)
    buildFullPath(root)
    menus.value = root.children
    needLoadRoutes.value = false
    return root.children
  }

  return { menus, leafRoutes, getRoutes, needLoadRoutes }
})

/**
 * buildFullPath
 */
const buildFullPath = (tree) => {
  tree.children.forEach((child) => {
    child.fullPath = tree.fullPath +'/'+ child.path
    buildFullPath(child)
  })
}

// // 构建出一棵树状结构的路由
// const buildTree = (routes) => {
//   // 此处添加params并不会在跳转路由时传params，此时添加params属性，是为了给menus侧边栏用的，通过侧边栏把params传给路由
//   routes.forEach((item) => {
//     if (item.params) {
//       item.params = JSON.parse(item.params)
//     }
//   })
//   routes.forEach((item) => {
//     routeMap.set(item.id, item)
//     item.fullPath = item.path
//     if (item.perm) {
//       item.component = modules['/src/views/' + item.component + '.vue']
//       item.meta = { perm: item.perm }
//     }
//     //可以不给叶子节点加children
//     item.children = []
//   })
//   routes.forEach((item) => {
//     let parent = routeMap.get(item.parentId)
//     item.fullPath = parent.fullPath + item.fullPath
//     parent.children.push(item)
//   })
//   return root
// }

/**
 * 过滤出用户拥有权限的路由
 * @param tree：路由树
 * @param perms:拥有的权限
 * @returns {*|null} 返回过滤后的路由树
 */
const filterRoutes = (tree) => {
  if (!hasPermi(tree)) {
    return null
  }
  let children = []
  tree.children.forEach((child) => {
    let next = filterRoutes(child)
    if (next) {
      children.push(next)
    }
  })
  tree.component = modules['/src/views/' + tree.component + '.vue']
  /*如果是叶子节点，直接返回*/
  if (tree.children.length === 0) {
    return tree
  }
  tree.children = children

  return children.length > 0 ? tree : handleEmptyChildren(tree)
}

const hasPermi = (route) => {
  // if (route.perm) {
  //   return perms.has(route.perm + ':list')
  // }
  return true
}

const handleEmptyChildren = (tree) => {
  return tree.always_show ? tree : null
}
